package com.springcloud.authentication.modules.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.springcloud.authentication.common.RestResult;
import com.springcloud.authentication.common.RestResultEntity;
import com.springcloud.authentication.common.jwt.Audience;
import com.springcloud.authentication.common.jwt.JwtHelper;
import com.springcloud.authentication.modules.entity.SysUser;
import com.springcloud.authentication.modules.service.SysUserService;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;


/**
 * 用户表
 * @author Administrator
 *
 */

@RestController
@RequestMapping("/api/authorization")
public class LoginController {

	private static final Logger logger = LogManager.getLogger(LoginController.class); 


	@Autowired
	private SysUserService userService;


	@RequestMapping("/list")
	public List<SysUser> list() {
		return userService.findList();
	}

	/**
	 * 用户登录，颁发token令牌
	 * @param user
	 * @return
	 */
	@RequestMapping("/login")
	public RestResultEntity<?> login(String name,String pwd) {
		SysUser user =  userService.getUser(name,pwd);
		if (user == null) {
			return RestResult.genErrorResult("401","用户或密码错误"); 
		}
		return RestResult.genResult(userService.getToken(user));
	}



	/**
	 * 验证token令牌
	 * @param token	token
	 * @return
	 */
	@RequestMapping("/validToken")
	public RestResultEntity<?> verification(String token,String type) {
		// 验证token合法
		RestResultEntity<?> verification = userService.verification(token);
		if("1".equals(type)) { //校验刷新的token是否过期，如果没有过期则生成新的token
			if("200".equals(verification.getCode())) {
				Claims claims = (Claims)verification.getData();
				SysUser user =  userService.findById(claims.get("userid").toString());
				return  RestResult.genResult(userService.getToken(user)); //生成token
			}
		}
		return  verification; 
	}
}
